import type { Router } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import useUserStore from '@/store/modules/user.js'
import { routes } from './routes.js'
import whiteList from './whiteList.js'

const router: Router = createRouter({
  // history: createWebHashHistory(),// 哈希模式
  history: createWebHistory(), // history模式
  routes,
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      }
      else {
        if (from.meta.saveSrollTop) {
          const top: number
            = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  },
})

router.beforeEach(async (to, from, next) => {
  // to and from are both route objects. must call `next`.
  const userStore = useUserStore()
  const token = userStore.getToken()
  // 白名单放行
  if (whiteList.find(val => val === to.path))
    return next()
  if (!token)
    return next(`/login?redirect=${to.path}`)
  // 已登录放行
  if (userStore.RoleMap && userStore.RoleMap.length)
    return next()
  // 如果没有RoleMap等信息用户可能清除了本地仓库信息，重新获取保存的用户信息登录（例如刷新操作）
  //   这里正常操作应该是通过token获取用户信息。目前APS系统总无法支持
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '')
  const loginRes = await userStore
    .userLogin({ Account: userInfo?.Account, Pwd: userInfo?.Pwd })
  if (loginRes) {
    next({ ...to, replace: true })
  }
  else {
    if (to.path)
      next(`/login?redirect=${to.path}`)
    else next(`/login`)
  }
})

router.afterEach((to) => {
  document.title = to.meta.title as string
})

export default router
